package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.StampedLock;

import static cn.itcast.n2.util.Sleeper.sleep;

@Slf4j(topic = "c.TestReadWriteLock")
public class TestReadWriteLock {
    public static void main(String[] args) throws InterruptedException {
        final Datacontainer datacontainer = new Datacontainer();
        new Thread(()->{
//            datacontainer.read();
            datacontainer.write();
        },"t1").start();

        Thread.sleep(100);
        new Thread(()->{
//            datacontainer.read();
            datacontainer.write();
        },"t2").start();
    }
}

@Slf4j(topic = "c.Datacontainer")
class Datacontainer{
    private Object data;
    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = rw.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = rw.writeLock();

    public Object read(){
        log.debug("获取读锁...");
        readLock.lock();
        try {
            log.debug("读取");
            sleep(1);
            return data;
        }finally {
            log.debug("释放读锁...");
            readLock.unlock();
        }
    }

    public void write(){
        log.debug("获取写锁...");
        writeLock.lock();
        try {
            log.debug("写入");
            sleep(1);
        }finally {
            log.debug("释放写锁...");
            writeLock.unlock();
        }
    }
}
